<template>
  <div>
    <!-- Vertical bar chart -->
    <canvas ref="chart" class="chart-bar" :style="{'height': height + 'px'}"></canvas>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

export default ({
  props: [
    'data',
    'height',
  ],
  data(){
    return {
      chart: null,
    };
  },
  mounted () { 
    let ctx = this.$refs.chart.getContext("2d");
    this.chart = new Chart(ctx, {
      type: "bar",
      data: this.data,
      options: {
        indexAxis: 'x', // 设置为x轴为基准轴（竖向柱状图）
        layout: {
          padding: {
            top: 30,
            right: 15,
            left: 10,
            bottom: 5,
          },
        },
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: true, // 显示图例
            position: 'top', // 图例位置
          },
          tooltip: {
            enabled: true,
            mode: "index",
            intersect: false,
          },
        },
        scales: {
          y: {
            beginAtZero: true, // y轴从0开始
            grid: {
              display: true,
              color: "rgba(0, 0, 0, 0.1)",
            },
            ticks: {
              color: "#666",
              font: {
                size: 12,
                family: "Arial",
              },
            },
            title: {
              display: true,
              text: '次数/百分比', // y轴标题
              color: "#666",
            }
          },
          x: {
            grid: {
              display: false,
            },
            ticks: {
              color: "#666",
              font: {
                size: 12,
                family: "Arial",
              },
            },
          },
        },
      }
    });
  },
  beforeDestroy() {
    this.chart.destroy();
  },
})
</script>

<style lang="scss" scoped>
.chart-bar {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>